<template>
  <view class="wrap">
    <view class="container">
      <uni-forms ref="form" :model="form" labelWidth="60px" label-position="top">
        <uni-forms-item label="标题" name="title">
          <uni-easyinput v-model="form.title" placeholder="请输入标题" />
        </uni-forms-item>
        <uni-forms-item label="内容" name="content">
          <uni-easyinput v-model="form.content" autoHeight type="textarea" maxlength="-1" class="item-textarea" placeholder="请输入内容" />
        </uni-forms-item>
        <uni-forms-item label="图片">
          <uni-file-picker
            :value="filterImageList"
            :limit="1000"
            title=""
            file-mediatype="image"
            @select="handleUploadImage"
            @delete="handleDeleteImage"
            :readonly="isEditDisable" ref="uniFilePicker"></uni-file-picker>
        </uni-forms-item>
        <uni-forms-item v-if="form.updateTime" label="修改时间" name="updateTime">
          <uni-easyinput :value="form.updateTime" :disabled="true" :clearable="false" />
        </uni-forms-item>
        <uni-forms-item v-if="form.createTime" label="创建时间" name="createTime">
          <uni-easyinput :value="form.createTime" :disabled="true" :clearable="false" />
        </uni-forms-item>
      </uni-forms>
      <div class="footer-fixed">
        <u-button @click="handleSubmit" class="btn-submit" type="primary">保存</u-button>
      </div>
    </view>
  </view>
</template>

<script>
	import { strer, dater } from '@daelui/dogjs/dist/components.js'
  import noteSer from '@/api/service/note.js'
  import fileSer, { deleteLocalFile } from '@/api/service/file.js'
  import uniFiler from '@/components/libs/uni-filer.js'
  import { compress } from '@/components/libs/imager.js'
  
  export default {
    data() {
      return {
				params: {},
        form: {
          title: "",
          content: "",
					createTime: '',
					updateTime: ''
        },
        rules: {
          title: {
            rules: [{
              required: true,
              errorMessage: '不能为空'
            }]
          },
          content: {
            rules: [{
              required: true,
              errorMessage: '不能为空'
            }]
          }
        },
        imageList: [],
        isEditDisable: false
      }
    },
    
    computed: {
      filterImageList () {
        return this.imageList.filter(item => {
          return !item.isDelete
        })
      }
    },
    
    onLoad(params) {
    	this.params = params
			this.initView()
    },
    onReady() {

    },

    mounted () {
      let uniFilePicker = this.$refs.uniFilePicker
      Object.defineProperty(uniFilePicker, 'limitLength', {
        get () {
          if (this.returnType === 'object') {
            return 1
          }
          return 1000
        }
      })
    },
    
    methods: {
			async initView () {
				let params = this.params || {}
				let node = await noteSer.queryItem({ id: params.id || -9999 })
				if (node) {
					this.isEdit = true
					this.form = node
          let images = node.images
          if (images) {
            fileSer.queryList({ id: images }, { operators: [{field: 'id', operator: 'IN'}] }).then(res => {
              let list = Array.isArray(res) ? res : []
              this.imageList = list.map(item => {
                return {
                  id: item.id,
                  name: item.name,
                  url: item.path
                }
              })
            })
          }
				}
			},
      // 上传图片
      handleUploadImage (args) {
        let imageList = [...this.imageList]
        this.imageList = imageList
        let user = this.getCurrentUser() || {}
        let defer = Promise.resolve(true)
        args.tempFilePaths.forEach((path, i) => {
          let node = args.tempFiles[i].file
          defer = defer.finally(() => {
            // 压缩
            return compress({ src: path, quality: 94 }).then((text) => {
              return uniFiler.base64ToPath(text).then(path => {
                let image = {
                  id: strer.udigit(),
                  name: node.name,
                  saveName: node.name,
                  path: path,
                  url: path,
                  createUserId: user.userId,
                  isInsert: 1
                }
                this.imageList.push(image)
              })
            })
          })
        })
      },
      // 删除图片
      handleDeleteImage (args) {
        let node = args.tempFile
        let id = node.id
        // 本地添加的图片直接删除
        this.imageList.forEach(function(item){
          if (String(item.id) === String(id)) {
            // 删除项标记
            item.isDelete = 1
            // 刚添加的则直接删除
            if (item.isInsert) {
              deleteLocalFile(item)
              return false
            }
          }
          return true
        })
      },
			handleSubmit () {
				this.$refs.form.validate().then(res => {
					this.save()
				})
			},
			save () {
				let defer = Promise.resolve()
        let user = this.getCurrentUser()
				if (!this.isEdit) {
					let time = dater.format(new Date())
					this.form.id = strer.udigit()
					this.form.createTime = time
          this.form.userId = user.userId
					defer = noteSer.insert(this.form)
				} else {
					this.form.updateTime = dater.format(new Date())
					defer = noteSer.update(this.form)
				}
				defer.then(() => {
					this.$u.toast('操作成功')
          uni.$emit('onRefreshNoteList')
          this.saveImages().finally(() => {
            this.goBack()
          })
				}).catch(() => {
					this.$u.toast('操作失败')
				})
			},
      saveImages () {
        let inserts = [], deletes = []
        this.imageList.forEach(item => {
          if (item.isInsert) {
            inserts.push(item)
          } else if (item.isDelete) {
            deletes.push(item)
          }
        })
        let ids = this.imageList.filter(item => {
          return !item.isDelete
        }).map(item => item.id).join(',')
        return fileSer.insert(inserts).finally(() => {
          return fileSer.deleteList(deletes)
        }).then(() => {
          this.form.images = ids
          return noteSer.update(this.form)
        }).catch(e => {
          console.log(e)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #ffffff;
  }
  .container {
    padding: 15px 15px 80px;
    background-color: #fff;
  }
  .footer-fixed {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 12px;
    background: #fff;
    border-top: 1px #ebeef5 solid;
    z-index: 9;
    .btn-submit {
      width: 100%;
    }
  }
</style>
